<template>
  <el-card class="el-card--has-heading success">
    <div slot="header" class="v-card__headerInner">
      <p>充值活动</p>
      <el-button
        class="v-card__headerAction"
        type="text"
        @click="onClickCreate"
        v-auth:[$P.productOperation.recharge.create]
      >{{showForm ? '返回列表' : '创建充值活动'}}</el-button>
    </div>

    <transition name="scale-ani">
      <RechargeForm
        :record="record"
        @submit="handleSubmit"
        v-loading="formLoading"
        ref="RechargeForm"
        v-if="showForm"
      />
      <v-table
        :dataSource="dataSource"
        :columns="filterColumn(columns, [$P.productOperation.recharge.update,$P.productOperation.recharge.delete])"
        :loading="loading"
        :total="total"
        v-else
        v-bind="bindProps"
        v-on="bindListeners"
      >
        <template slot="toolbar">
          <el-form inline size="small" :model="query" ref="query" class="flex flex-wrap">
            <el-form-item prop="rechargeActivityName">
              <el-input placeholder="请输入活动名称" v-model.trim="query.rechargeActivityName" />
            </el-form-item>

            <el-form-item prop="rechargeActivityState">
              <el-select v-model="query.rechargeActivityState" placeholder="请选择活动状态">
                <el-option
                  v-for="(it, i) in onlineStatus"
                  :key="i"
                  :label="it.label"
                  :value="+it.value === 1 ? 'online' : 'offline'"
                ></el-option>
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="success" @click="handleSearch">查询</el-button>
              <el-button type="warning" @click="handleReset">重置</el-button>
            </el-form-item>
          </el-form>
        </template>
      </v-table>
    </transition>
  </el-card>
</template>

<script>
import {
  getRechargeList,
  createRecharge,
  updateRecharge,
  deleteRecharge,
  getRechargeById,
  offlineRecharge,
  onlineRecharge,
  getCouponByIds
} from '@/api'

/* components
---------------------------------------------------------------- */
import RechargeForm from './components/RechargeForm'
import { Query } from '@/mixins'

/* model
---------------------------------------------------------------- */
import { primaryKey } from './model'
import { onlineStatusEnum } from '@/core/enum'

export default {
  mixins: [Query('query')],

  data () {
    return {
      total: 0,
      dataSource: [],
      loading: false,
      columns: [
        { prop: 'rechargeActivityName', label: '名称' },
        {
          prop: 'rechargeActivityStartTime',
          label: '开始时间'
        },
        {
          prop: 'rechargeActivityEndTime',
          label: '结束时间'
        },
        {
          prop: 'rechargeActivityStateValue',
          label: '活动状态',
          formatter: (row) => (
            <el-link
              type={
                row['rechargeActivityState'].toLowerCase() !== 'online'
                  ? 'danger'
                  : 'success'
              }
              onClick={() =>
                this.toggleOnline(
                  row['rechargeActivityState'].toLowerCase() !== 'online',
                  row
                )
              }
            >
              {row['rechargeActivityStateValue']}
            </el-link>
          )
        },
        {
          prop: 'rechargeActivityCreateTime',
          label: '创建时间',
          width: this.$V.cellSize.date,
          formatter: (row) =>
            this.$formatTime(row['rechargeActivityCreateTime'])
        },
        { prop: 'rechargeActivityCreateUserName', label: '创建人' },
        {
          prop: 'rechargeActivityUpdateTime',
          label: '修改时间',
          width: this.$V.cellSize.date,
          formatter: (row) =>
            this.$formatTime(row['rechargeActivityUpdateTime'])
        },
        { prop: 'rechargeActivityUpdateUserName', label: '修改人' },
        {
          label: '操作',

          minWidth: this.$V.cellSize.action,
          formatter: this.getActionDecorator([
            {
              icon: 'el-icon-edit',
              action: this.onClickUpdate,
              type: 'primary',
              auth: this.$P.productOperation.recharge.update
            },
            {
              icon: 'el-icon-delete',
              action: this.onClickDelete,
              type: 'danger',
              auth: this.$P.productOperation.recharge.delete
            }
          ])
        }
      ],
      record: {},
      query: {},

      // -------- Form ----------
      showForm: false,
      formLoading: false,
      actionType: ''
      // -------- !Form ----------
    }
  },
  methods: {
    // Requests
    // ------------------------------------------
    getRechargeList (fn) {
      return this.Catch(getRechargeList, {
        onOk (res) {
          this.dataSource = res.data.data
          this.total = res.data.total
        }
      })('loading', (fn || this.$noop)(this.query))
    },

    getCouponByIds (ids, { onOk, onError }) {
      return this.Catch(getCouponByIds, {
        onOk,
        onError
      })('loading', ids)
    },

    getRechargeById (id, { onOk, onError }) {
      return this.Catch(getRechargeById, {
        onOk,
        onError
      })('loading', id)
    },

    deleteRecharge (id, { onOk }) {
      return this.Catch(deleteRecharge, {
        onOk
      })(null, id)
    },

    onlineRecharge (id) {
      return this.Catch(onlineRecharge, {
        onOk () {
          this.$message.success('上线成功')
          this.getRechargeList()
        }
      })(null, id)
    },

    offlineRecharge (id) {
      return this.Catch(offlineRecharge, {
        onOk () {
          this.$message.success('下线成功')
          this.getRechargeList()
        }
      })(null, id)
    },

    createRecharge (data) {
      return this.Catch(createRecharge, {
        onOk () {
          this.$message.success(this.$t('createOk'))
          this.showForm = false
          this.getRechargeList()
        }
      })('formLoading', data)
    },

    updateRecharge (id, data) {
      return this.Catch(updateRecharge, {
        onOk () {
          this.$message.success(this.$t('updateOk'))
          this.showForm = false
          this.getRechargeList()
        }
      })('formLoading', id, data)
    },

    // Table
    // ------------------------------------------

    onClickDelete (row) {
      this.ConfirmDelete({
        onOk: () =>
          this.deleteRecharge(row[primaryKey], {
            onOk () {
              this.$message.success(this.$t('deleteOk'))
              this.getRechargeList()
            }
          })
      })
    },

    /**
     * 切换上下线
     */
    toggleOnline (willOnline, row) {
      this.ConfirmToggleOnline({
        online: willOnline,
        onOk: () =>
          willOnline
            ? this.onlineRecharge(row[primaryKey])
            : this.offlineRecharge(row[primaryKey])
      })
    },

    async onClickUpdate (row) {
      try {
        this.assertCanUpdate(row)

        this.actionType = 'update'
        this.getRechargeById(row[primaryKey], {
          onOk ({ data }) {
            if (
              data.rechargeActivityStartTime &&
              data.rechargeActivityEndTime
            ) {
              data._dateRange = [
                data.rechargeActivityStartTime,
                data.rechargeActivityEndTime
              ]
            }
            const showForm = (data) => {
              this.record = data
              this.showForm = true
            }
            let tasks = []
            if (data.rechargeDiscountList && data.rechargeDiscountList.length) {
              data.rechargeDiscountList.forEach((d) => {
                if (d.rechargeDiscountGiveCoupon) {
                  let ids = d.rechargeDiscountGiveCoupon.split(',')
                  tasks.push(
                    this.getCouponByIds(ids, {
                      onOk ({ data }) {
                        d._rechargeDiscountGiveCoupon = data
                      },
                      onError () {}
                    })
                  )
                }
              })
            }

            if (tasks.length) {
              Promise.all(tasks).then(() => showForm(data))
            } else {
              showForm(data)
            }
          }
        })
      } catch (err) {
        this.$message.warning(err.message)
      }
    },

    async onClickCreate () {
      this.actionType = 'create'
      this.record = {}

      this.showForm = !this.showForm
    },

    // ------------------------------------------ Form 开始------------------------------------------

    assertCanUpdate (row) {
      if (row['rechargeActivityState'].toLowerCase() === 'online') {
        throw new Error('上线状态不可编辑')
      }
    },

    handleSubmit (valid, formData) {
      this.actionType === 'create'
        ? this.createRecharge(formData)
        : this.updateRecharge(formData[primaryKey], formData)
    }
    // ------------------------------------------ Form 结束------------------------------------------
  },
  computed: {
    onlineStatus () {
      return this.$mapEnumToSelect(onlineStatusEnum)
    }
  },
  components: { RechargeForm },

  created () {
    this.getRechargeList()
    this.inject(this.getRechargeList)
  }
}
</script>
